import * as docx from "docx";
import { Document, Paragraph, TextRun, AlignmentType } from "docx";
import { saveAs } from "file-saver";
/**
 * 将HTML内容导出为Word文档（去掉第一页）
 * @param {string} htmlContent - 包含特定类名的HTML内容
 * @param {string} name - 导出文件的名称
 */
export async function exportWord(htmlContent, name) {
    console.log(htmlContent);

    // 等待docx库加载完成
    if (typeof docx === 'undefined') {
        console.error('文档生成库正在加载中，请稍后再试...');
        return;
    }

    // 初始化文档各部分内容变量
    let docNumber = "";      // 文档编号
    let mainTitle = "";      // 主标题
    let publishInfo = "";    // 发布信息
    let contentChildren = [];// 正文内容子元素

    if (htmlContent) {
        // HTML解码函数，解决HTML格式被转义的问题
        const decodeHtml = (html) => {
            const txt = document.createElement('textarea');
            txt.innerHTML = html;
            return txt.value;
        };

        // 对htmlContent进行解码
        htmlContent = decodeHtml(htmlContent);

        // 去除htmlContent中的<body>标签
        if (htmlContent.includes('<body')) {
            const bodyStart = htmlContent.indexOf('<body');
            const bodyEndStart = htmlContent.indexOf('>', bodyStart);
            const bodyEnd = htmlContent.indexOf('</body>');

            if (bodyStart !== -1 && bodyEndStart !== -1 && bodyEnd !== -1) {
                // 提取body标签中的内容
                htmlContent = htmlContent.substring(bodyEndStart + 1, bodyEnd);
            } else if (bodyStart !== -1 && bodyEndStart !== -1) {
                // 只有开始标签，没有结束标签
                htmlContent = htmlContent.substring(bodyEndStart + 1);
            }
        }

        // 创建临时DOM元素来解析HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;

        const numberElement = tempDiv.querySelector('.top_red_line_left_right');
        if (numberElement && numberElement.textContent) {
            docNumber = numberElement.textContent.trim();
        }

        // 查找具有main-title类的元素作为主标题
        const mainTitleElement = tempDiv.querySelector('.main-title');
        if (mainTitleElement && mainTitleElement.textContent) {
            mainTitle = mainTitleElement.textContent.trim();
        }

        // 按照元素在文档中出现的顺序处理所有指定类名的元素
        const allElements = tempDiv.querySelectorAll('.recipient,.lead,.level1, .level2, .content, .cc-text, .signature, .row_content');
        allElements.forEach(element => {
            const classNames = element.className.split(' ');
            const text = element.textContent.trim();

            // 根据不同类名应用不同的格式处理
            if (classNames.includes('recipient')) {
                // 收件人信息：仿宋_GB2312，16pt
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" }
                }));
            } else if (classNames.includes('lead')) {
                // 负责人信息：仿宋_GB2312，16pt
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" }
                }));
            } else if (classNames.includes('level1')) {
                // 一级标题：仿宋_GB2312，16pt，加粗
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" },
                    bold: true
                }));
            } else if (classNames.includes('level2')) {
                // 二级标题：仿宋_GB2312，16pt，加粗
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" },
                    bold: true
                }));
            } else if (classNames.includes('content')) {
                // 正文内容：仿宋_GB2312，16pt，首行缩进
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" },
                    firstLineIndent: 800
                }));
            } else if (classNames.includes('row_content')) {
                // 行内容：仿宋_GB2312，16pt，首行缩进（较大）
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" },
                    firstLineIndent: 1000,
                    spacing: { after: 200 }
                }));
            } else if (classNames.includes('cc-text')) {
                // 抄送信息：仿宋_GB2312，15pt，1.5倍行距
                contentChildren.push(createParagraph(text, {
                    size: 30,
                    font: { name: "仿宋_GB2312" },
                    spacing: {
                        after: 250,
                        line: 480
                    }
                }));
            } else if (classNames.includes('signature')) {
                // 落款/说明：仿宋_GB2312，16pt，右对齐
                contentChildren.push(createParagraph(text, {
                    size: 32,
                    font: { name: "仿宋_GB2312" },
                    alignment: AlignmentType.RIGHT,
                    spacing: { before: 100, after: 150 }
                }));
            }
        });

        // 查找具有publish-info类的元素作为发布信息
        const publishInfoElement = tempDiv.querySelector('.publish-info');
        if (publishInfoElement && publishInfoElement.textContent) {
            publishInfo = publishInfoElement.textContent.trim();
        }
    }

    // 构建内容部分的段落（添加主标题和发布信息）
    const fullContentChildren = [];

    // 添加文档编号：黑体，14pt，居中（原第一页的内容移到正文开头）
    if (docNumber) {
        fullContentChildren.push(
            new Paragraph({
                children: [
                    new TextRun({
                        text: docNumber,
                        size: 28,
                        font: { name: "黑体" }
                    })
                ],
                alignment: AlignmentType.CENTER,
                spacing: {
                    after: 400,
                    before: 100
                }
            })
        );
    }

    // 添加主标题：方正小标宋简体，22pt，居中
    fullContentChildren.push(
        new Paragraph({
            children: [
                new TextRun({
                    text: mainTitle,
                    size: 44,
                    font: { name: "方正小标宋简体" }
                })
            ],
            alignment: AlignmentType.CENTER,
            spacing: {
                after: 400,
                before: 38
            }
        })
    );

    // 添加按顺序处理的内容
    fullContentChildren.push(...contentChildren);

    // 添加发布信息：仿宋_GB2312，14pt
    fullContentChildren.push(
        new Paragraph({
            children: [
                new TextRun({
                    text: publishInfo,
                    size: 28,
                    font: { name: "仿宋_GB2312" }
                })
            ],
            spacing: { after: 100 }
        })
    );

    // 创建文档，只保留内容页（已移除第一页）
    const doc = new Document({
        sections: [{
            // 只保留一个章节，即原内容页部分
            properties: {},
            children: fullContentChildren
        }]
    });

    try {
        // 生成并下载文件
        const blob = await docx.Packer.toBlob(doc);
        saveAs(blob, name);
    } catch (error) {
        console.error("导出文档时出错:", error);
        alert("导出文档时出错，请查看控制台了解详细信息。");
    }
}

/**
 * 创建段落的辅助函数
 * @param {string} text - 段落文本内容
 * @param {Object} options - 格式选项
 * @returns {Paragraph} - 创建的段落对象
 */
function createParagraph(text, options = {}) {
    const { size, font, bold, firstLineIndent, spacing, alignment } = options;

    // 默认段后间距
    const defaultSpacing = { after: 300 };

    return new Paragraph({
        children: [
            new TextRun({
                text,
                size,
                font,
                bold
            })
        ],
        indent: firstLineIndent ? {
            firstLine: firstLineIndent
        } : {},
        spacing: spacing || defaultSpacing,
        alignment: alignment
    });
}
